// utils/api.js

// 请求封装
function request(url, method, data = {}) {
  return new Promise((resolve, reject) => {
    // 获取app实例，如果获取失败则使用默认值
    const app = getApp()
    const globalData = app ? app.globalData : { token: '' }
    
    // 管理员方法不需要Authorization头，使用session认证
    const adminMethods = [
      '/scanwork/getOrders', '/scanwork/getAllocations', '/scanwork/getReports', 
      '/scanwork/auditReport', '/scanwork/getReportDetail', '/scanwork/getProducts', 
      '/scanwork/getProcesses', '/scanwork/getUsers', '/scanwork/createAllocation', 
      '/scanwork/batchCreateAllocation', '/scanwork/getOrderModels', 
      '/scanwork/getOrderDetail', '/scanwork/createOrder', '/scanwork/updateOrder', 
      '/scanwork/deleteOrder', '/scanwork/adminLogin', '/scanwork/checkToken',
      '/scanwork/getActiveReports', '/scanwork/getActiveReportDetail', '/scanwork/auditActiveReport',
      '/scanwork/getProductList', '/scanwork/createProduct', '/scanwork/updateProduct', '/scanwork/deleteProduct',
      '/scanwork/getProductModelList', '/scanwork/createProductModel', '/scanwork/updateProductModel', '/scanwork/deleteProductModel',
      '/scanwork/getProcessList', '/scanwork/createProcess', '/scanwork/updateProcess', '/scanwork/deleteProcess',
      '/scanwork/getProcessPriceList', '/scanwork/createProcessPrice', '/scanwork/updateProcessPrice', '/scanwork/deleteProcessPrice', '/scanwork/batchProcessPrice',
      '/scanwork/getAdminPermissions', '/scanwork/getOrderProgressList', '/scanwork/getProcessProgressStats', '/scanwork/getOrderProgressDetail', '/scanwork/getProgressFilterOptions'
    ];
    
    const isAdminMethod = adminMethods.some(method => url.includes(method));
    
    const headers = {
      'content-type': 'application/json'
    };
    
    // 所有方法都添加Authorization头（如果token存在）
    if (globalData.token) {
      headers['Authorization'] = 'Bearer ' + globalData.token;
    }
    
    wx.request({
      url: globalData.baseUrl + url,
      method: method,
      data: data,
      header: headers,
              success: (res) => {
          console.log('API响应:', res.data)
          if (res.statusCode === 200) {
            if (res.data.code == 1) {
              resolve(res.data)
            } else {
              // 检查权限错误
              if (res.data.msg && res.data.msg.includes('权限')) {
                wx.showModal({
                  title: '权限不足',
                  content: res.data.msg,
                  showCancel: false,
                  success: () => {
                    // 跳转到登录页面或首页
                    wx.reLaunch({
                      url: '/pages/login/login'
                    });
                  }
                });
                reject(res.data);
                return;
              }
              
              wx.showToast({
                title: res.data.msg || '请求失败',
                icon: 'none'
              })
              reject(res.data)
            }
          } else if (res.statusCode === 401) {
            // 401错误，跳转到登录页
            wx.showToast({
              title: '请先登录',
              icon: 'none'
            })
            wx.reLaunch({
              url: '/pages/login/login'
            })
            reject(res)
          } else if (res.statusCode === 403) {
            // 403权限错误
            wx.showModal({
              title: '权限不足',
              content: '您没有权限执行此操作',
              showCancel: false,
              success: () => {
                wx.reLaunch({
                  url: '/pages/login/login'
                });
              }
            });
            reject(res);
          } else {
            wx.showToast({
              title: '网络错误',
              icon: 'none'
            })
            reject(res)
          }
        },
      fail: (err) => {
        wx.showToast({
          title: '请求失败',
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}

// API方法
const api = {
  // 获取订单型号
  getOrderModels(orderId) {
    return request('/scanwork/getOrderModels', 'GET', { order_id: orderId })
  },

  // 获取订单列表
  getOrders(params = {}) {
    return request('/scanwork/getOrders', 'GET', params)
  },

  // 获取订单详情
  getOrderDetail(orderId) {
    return request('/scanwork/getOrderDetail', 'GET', { order_id: orderId })
  },

  // 创建订单
  createOrder(data) {
    return request('/scanwork/createOrder', 'POST', data)
  },

  // 更新订单
  updateOrder(orderId, data) {
    return request('/scanwork/updateOrder', 'POST', { order_id: orderId, ...data })
  },

  // 删除订单
  deleteOrder(orderId) {
    return request('/scanwork/deleteOrder', 'POST', { order_id: orderId })
  },

  // 获取分工任务列表
  getAllocations(params) {
    return request('/scanwork/getAllocations', 'GET', params)
  },

  // 获取我的分工任务
  getMyAllocations(params) {
    return request('/scanwork/getMyAllocations', 'GET', params)
  },

  // 提交报工
  submitReport(data) {
    return request('/scanwork/submitReport', 'POST', data)
  },

  // 上传报工图片
  uploadReportImage(reportId, filePath) {
    return new Promise((resolve, reject) => {
      const app = getApp()
      const globalData = app ? app.globalData : { baseUrl: 'https://order.023ent.net/api', token: '' }
      
      wx.uploadFile({
        url: globalData.baseUrl + '/scanwork/uploadReportImage',
        filePath: filePath,
        name: 'image',
        formData: {
          report_id: reportId
        },
        header: {
          'Authorization': 'Bearer ' + globalData.token
        },
        success: (res) => {
          const data = JSON.parse(res.data)
          if (data.code === 1) {
            resolve(data)
          } else {
            wx.showToast({
              title: data.msg || '上传失败',
              icon: 'none'
            })
            reject(data)
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          })
          reject(err)
        }
      })
    })
  },

  // 上传审核图片
  uploadAuditImage(reportId, filePath) {
    return new Promise((resolve, reject) => {
      const app = getApp()
      const globalData = app ? app.globalData : { baseUrl: 'https://order.023ent.net/api', token: '' }
      
      wx.uploadFile({
        url: globalData.baseUrl + '/scanwork/uploadAuditImage',
        filePath: filePath,
        name: 'audit_images',
        formData: {
          report_id: reportId
        },
        success: (res) => {
          const data = JSON.parse(res.data)
          if (data.code === 1) {
            resolve(data)
          } else {
            wx.showToast({
              title: data.msg || '上传失败',
              icon: 'none'
            })
            reject(data)
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          })
          reject(err)
        }
      })
    })
  },

  // 获取报工列表
  getReports(params) {
    return request('/scanwork/getReports', 'GET', params)
  },

  // 获取主动报工列表
  getActiveReports(params) {
    return request('/scanwork/getActiveReports', 'GET', params)
  },

  // 获取报工详情
  getReportDetail(reportId) {
    return request('/scanwork/getReportDetail', 'GET', { report_id: reportId })
  },

  // 获取主动报工详情
  getActiveReportDetail(reportId) {
    return request('/scanwork/getActiveReportDetail', 'GET', { report_id: reportId })
  },

  // 审核报工
  auditReport(data) {
    return request('/scanwork/auditReport', 'POST', data)
  },

  // 审核主动报工
  auditActiveReport(data) {
    return request('/scanwork/auditActiveReport', 'POST', data)
  },

  // 审核普通报工
  auditReport(data) {
    return request('/scanwork/auditReport', 'POST', data)
  },

  // 获取产品列表
  getProducts() {
    return request('/scanwork/getProducts', 'GET')
  },

  // 获取产品型号列表
  getModels(params) {
    return request('/scanwork/getModels', 'GET', params)
  },

  // 获取工序列表
  getProcesses() {
    return request('/scanwork/getProcesses', 'GET')
  },

  // 获取员工列表
  getUsers() {
    return request('/scanwork/getUsers', 'GET')
  },

  // 管理员登录
  adminLogin(data) {
    return request('/scanwork/adminLogin', 'POST', data)
  },

  // 验证token
  checkToken() {
    return request('/scanwork/checkToken', 'GET')
  },

  // 创建分工任务
  createAllocation(data) {
    return request('/scanwork/createAllocation', 'POST', data)
  },

  // 批量创建分工任务
  batchCreateAllocation(data) {
    return request('/scanwork/batchCreateAllocation', 'POST', data)
  },

  // ==================== 产品管理 ====================
  
  // 获取产品列表
  getProductList(params) {
    return request('/scanwork/getProductList', 'GET', params)
  },

  // 创建产品
  createProduct(data) {
    return request('/scanwork/createProduct', 'POST', data)
  },

  // 更新产品
  updateProduct(data) {
    return request('/scanwork/updateProduct', 'POST', data)
  },

  // 删除产品
  deleteProduct(id) {
    return request('/scanwork/deleteProduct', 'POST', { id: id })
  },

  // ==================== 产品型号管理 ====================
  
  // 获取产品型号列表
  getProductModelList(params) {
    return request('/scanwork/getProductModelList', 'GET', params)
  },

  // 创建产品型号
  createProductModel(data) {
    return request('/scanwork/createProductModel', 'POST', data)
  },

  // 更新产品型号
  updateProductModel(data) {
    return request('/scanwork/updateProductModel', 'POST', data)
  },

  // 删除产品型号
  deleteProductModel(id) {
    return request('/scanwork/deleteProductModel', 'POST', { id: id })
  },

  // ==================== 工序管理 ====================
  
  // 获取工序列表
  getProcessList(params) {
    return request('/scanwork/getProcessList', 'GET', params)
  },

  // 创建工序
  createProcess(data) {
    return request('/scanwork/createProcess', 'POST', data)
  },

  // 更新工序
  updateProcess(data) {
    return request('/scanwork/updateProcess', 'POST', data)
  },

  // 删除工序
  deleteProcess(id) {
    return request('/scanwork/deleteProcess', 'POST', { id: id })
  },

  // ==================== 工序工价管理 ====================
  
  // 获取工序工价列表
  getProcessPriceList(params) {
    return request('/scanwork/getProcessPriceList', 'GET', params)
  },

  // 创建工序工价
  createProcessPrice(data) {
    return request('/scanwork/createProcessPrice', 'POST', data)
  },

  // 更新工序工价
  updateProcessPrice(data) {
    return request('/scanwork/updateProcessPrice', 'POST', data)
  },

  // 删除工序工价
  deleteProcessPrice(id) {
    return request('/scanwork/deleteProcessPrice', 'POST', { id: id })
  },

  // 批量设置工序工价
  batchProcessPrice(data) {
    return request('/scanwork/batchProcessPrice', 'POST', data)
  },

  // ==================== 权限管理 ====================
  
  // 获取管理员权限信息
  getAdminPermissions() {
    return request('/scanwork/getAdminPermissions', 'GET')
  },

  // 检查是否有权限执行某个操作
  checkPermission(module, action) {
    return new Promise((resolve, reject) => {
      this.getAdminPermissions().then(res => {
        if (res.code === 1) {
          const permissions = res.data.permissions;
          const isSuperAdmin = res.data.is_super_admin;
          
          // 超级管理员拥有所有权限
          if (isSuperAdmin) {
            resolve(true);
            return;
          }
          
          // 检查具体权限
          const modulePermissions = permissions[module] || [];
          const hasPermission = modulePermissions.includes(action);
          
          if (hasPermission) {
            resolve(true);
          } else {
            reject(new Error(`没有权限执行操作: ${module}.${action}`));
          }
        } else {
          reject(new Error('获取权限信息失败'));
        }
      }).catch(err => {
        reject(err);
      });
    });
  },

  // 权限检查装饰器
  withPermission(module, action, apiCall) {
    return this.checkPermission(module, action).then(() => {
      return apiCall();
    });
  },

  // 管理员登录
  adminLogin(data) {
    return request('/scanwork/adminLogin', 'POST', data)
  },

  // 检查token
  checkToken() {
    return request('/scanwork/checkToken', 'GET')
  },

  // ==================== 管理员管理 ====================
  
  // 获取管理员列表
  getAdminList(params = {}) {
    return request('/scanwork/getAdminList', 'GET', params)
  },

  // 创建管理员
  createAdmin(data) {
    return request('/scanwork/createAdmin', 'POST', data)
  },

  // 更新管理员
  updateAdmin(data) {
    return request('/scanwork/updateAdmin', 'POST', data)
  },

  // 删除管理员
  deleteAdmin(id) {
    return request('/scanwork/deleteAdmin', 'POST', { id: id })
  },

  // 获取管理员详情
  getAdminDetail(id) {
    return request('/scanwork/getAdminDetail', 'GET', { id: id })
  },

  // ==================== 订单进度管理 ====================
  
  // 获取订单进度列表
  getOrderProgressList(params = {}) {
    return request('/scanwork/getOrderProgressList', 'GET', params)
  },

  // 获取工序进度统计
  getProcessProgressStats(params = {}) {
    return request('/scanwork/getProcessProgressStats', 'GET', params)
  },

  // 获取订单进度详情
  getOrderProgressDetail(orderId) {
    return request('/scanwork/getOrderProgressDetail', 'GET', { order_id: orderId })
  },

  // 获取筛选选项
  getProgressFilterOptions() {
    return request('/scanwork/getProgressFilterOptions', 'GET', {})
  }
}

module.exports = api 